$(function() {
	// 页面控件
	var $iChecks = $('.i-checks'); // 页面中的所有checkbox（iCheck）
	var $dataTable = $('#dataTable'); // 表格
	var $dataTableToolbar = $('#dataTableToolbar'); // 表格：工具栏
	var $btnAddToggle = $('#btnAddToggle'); // 表格：添加按钮
	var $btnEditToggle = $('#btnEditToggle'); // 表格：修改按钮
	var $btnRemoveToggle = $('#btnRemoveToggle'); // 表格：删除按钮
	var $btnCheckAll = $('#btnCheckAll'); // 表格：全选按钮
	var $btnInvertCheck = $('#btnInvertCheck'); // 表格：反选按钮
	var $btnUncheckAll = $('#btnUncheckAll'); // 表格：取消选择按钮
	
	var $editDialog = $('#editDialog'); // 添加/修改窗口
	var $editDialogLabel = $('#editDialogLabel'); // 添加/修改窗口：标题
	var $editForm = $('#editForm'); // 添加/修改窗口：表单
	var $enable = $('#enable'); // 添加/修改窗口：可用状态
	var $btnSave = $('#btnSave'); // 添加/修改窗口：保存按钮
	var $btnReset = $('#btnReset'); // 添加/修改窗口：重置按钮
	
	var $deleteConfirmDialog = $('#deleteConfirmDialog'); // 删除确认窗口（矿区下存在机架时）
	var $deleteConfirmTip = $('#deleteConfirmTip'); // 删除确认窗口（矿区下存在机架时）：提示信息
	var $deleteShelfCount = $('#deleteShelfCount'); // 删除确认窗口（矿区下存在机架时）：提示信息中的下属机架数
	var $moveForDeleteTip = $('#moveForDeleteTip'); // 删除确认窗口（矿区下存在机架时）：重新分配下属机架时未选择目标矿区的提示信息
	var $moveShelfs = $('#moveShelfs'); // 删除确认窗口（矿区下存在机架时）：重新分配下属机架checkbox
	var $chosenMoveForDelete = $('#chosenMoveForDelete'); // 删除确认窗口（矿区下存在机架时）：重新分配下属机架时的目标矿区下拉列表框
	var $btnDeleteConfirm = $('#btnDeleteConfirm'); // 删除确认窗口（矿区下存在机架时）：确认删除按钮
	
	initWidgets();
	initListeners();
	initValidators();
	
	var formData; // 表单数据
	var saveMode = 0; // 保存方式：1：添加；2：修改
	// 弹出添加窗口时使用的初始表单控件值
	var emptyData = {id:'', name:'', enable:true, remark:''};
	var datasTobeDeleted; // 将要删除的数据（要删除的矿区下有机架时使用）
	
	// 弹出添加窗口
	function openAddDialog() {
		$editDialogLabel.text('添加矿区');
		initFormData(emptyData);
		$editDialog.modal('show');
		saveMode = 1;
	}
	
	// 弹出修改窗口
	function openEditDialog(data) {
		$editDialogLabel.text('修改矿区');
		initFormData(data);
		$editDialog.modal('show');
		saveMode = 2;
	}

	// 弹出删除确认窗口
	function openRemoveDialog(datas) {
		var tableDatas = $dataTable.bootstrapTable('getData');
		var title = '';
		if (datas.length == 1) {
			title = '将删除矿区' + datas[0].name + '。';
		} else if(datas.length == tableDatas.length) {
			title = '将删除所有矿区。';
		} else {
			title = '将删除所选' + datas.length + '个矿区。';
		}
		
		var delIds = new Array(datas.length);
		var shelfCount = 0;
		for (var i = 0; i < datas.length; i++) {
			shelfCount += datas[i].shelfCount;
			delIds[i] = datas[i].id;
		}
		
		if (shelfCount == 0) {
			swal({
		        title: title,
		        type: "warning",
		        showCancelButton: true,
		        cancelButtonText : "让我再考虑一下…",
		        confirmButtonColor: "#ed5565",
		        confirmButtonText : "是的，我要删除！",
		        text: '删除操作无法恢复，请谨慎操作！'
		    }, function(isConfirm) {
				if (isConfirm) {
					doDelete(JSON.stringify(datas));
				}
			});
		} else { // 要删除的矿区下有机架时
			datasTobeDeleted = datas;
			$deleteConfirmTip.text(title);
			$deleteShelfCount.text(shelfCount);
			$moveForDeleteTip.hide();
			$chosenMoveForDelete.empty();
			$chosenMoveForDelete.append($('<option value=""></option>'));
			var allDatas = $dataTable.bootstrapTable('getData');
			for (var i = 0; i < allDatas.length; i++) {
				var data = allDatas[i];
				if (data.enable != true || $.inArray(data.id, delIds) != -1) {
					continue;
				}
				$chosenMoveForDelete.append($('<option></option>').val(data.id).html(data.name));
			}
			$chosenMoveForDelete.chosen('destroy').chosen({allow_single_deselect: true, width:'60%'});
			$deleteConfirmDialog.modal('show');
		}
	}
	
	// 初始化表单控件的值
	function initFormData(data) {
		formData = data;
		$.each(formData, function (key, value) {
			$('#' + key).val(value);
		});
		if (data.enable == true) {
			$enable.prop('checked', true);
		} else {
			$enable.prop('checked', false);
		}
		$editForm.validate().form();
	}
	
	// 重置表单
	function doReset() {
		initFormData(formData);
	}

	// 保存（修改或添加）
	function doSave() {
		var data = $editForm.serializeObject();
		if (data.enable) {
			data.enable = true;
		} else {
			data.enable = false;
		}
		var paramData = JSON.stringify(data);
		if (saveMode == 1) {
			doPost(paramData);
		} else if (saveMode == 2) {
			doPut(paramData);
		}
	}

	// 添加
	function doPost(data) {
		$.ajax({
			url: 'areas',
			type: 'POST',
			dataType: 'json',
			contentType: "application/json; charset=utf-8",
			data: data,
			success: function(result) {
				if (result.success) {
					toastr.success(result.message, '添加成功');
					$editDialog.modal('hide');
					$dataTable.bootstrapTable('refresh');
				} else {
					toastr.error(result.message, '添加失败');
				}
			},
			error: function(request, status, error) {
				toastr.error(error, '异常');
			}
		});
	}

	// 修改
	function doPut(data) {
		$.ajax({
			url: 'areas',
			type: 'PUT',
			dataType: 'json',
			contentType: "application/json; charset=utf-8",
			data: data,
			success: function(result) {
				if (result.success) {
					toastr.success(result.message, '修改成功');
					$editDialog.modal('hide');
				} else {
					toastr.error(result.message, '修改失败');
				}
				$dataTable.bootstrapTable('refresh');
			},
			error: function(request, status, error) {
				toastr.error(error, '异常');
				$dataTable.bootstrapTable('refresh');
			}
		});
	}

	// 删除
	function doDelete(data) {
		$.ajax({
			url: 'areas',
			type: 'DELETE',
			dataType: 'json',
			contentType: "application/json; charset=utf-8",
			data: data,
			success: function(result) {
				if (result.success) {
					toastr.success(result.message, '删除成功');
					$dataTable.bootstrapTable('refresh');
					$deleteConfirmDialog.modal('hide');
				} else {
					toastr.error(result.message, '删除失败');
				}
			},
			error: function(request, status, error) {
				toastr.error(error, '异常');
			}
		});
	}

	function getHeight() {
	    return $(window).height() - 40;
	}
	
	// 初始化表单验证
	function initValidators() {
		var validIcon = "<i class='fa fa-times-circle'></i> ";
		$editForm.validate({
			rules: {
				name: { required: true, minlength: 2, maxlength: 80 },
				remark: { required: false, maxlength: 300 }
			},
			messages: {
				name: validIcon + '矿区名称须为2-80个字符。',
				remark: validIcon + '备注不能超过300个字符。'
			}
		});
	}

	// 初始化事件监听
	function initListeners() {
		$(window).resize(function () {
			$dataTable.bootstrapTable('resetView', {
	            height: getHeight()
	        });
	    });
		
		// 添加/修改窗口：保存按钮
		$btnSave.on('click', function() {
			var valid = $editForm.validate().form();
			if (!valid) {
				return;
			}
			doSave();
		});
		// 添加/修改窗口：重置按钮
		$btnReset.on('click', function() {
			doReset();
		});
		
		// 表格：添加按钮
		$btnAddToggle.on('click', function() {
			openAddDialog();
		});
		// 表格：修改按钮
		$btnEditToggle.on('click', function() {
			var selections = $dataTable.bootstrapTable('getSelections');
			if (selections.length == 0) {
				toastr.warning('请选择一个要修改的矿区。', '提示');
				return;
			} else if (selections.length > 1) {
				toastr.warning('只能选择一个矿区进行修改。', '提示');
				return;
			}
			openEditDialog(selections[0]);
		});
		// 表格：删除按钮
		$btnRemoveToggle.on('click', function() {
			var selections = $dataTable.bootstrapTable('getSelections');
			if (selections.length == 0) {
				toastr.warning('请选择要删除的矿区。', '提示');
				return;
			}
			openRemoveDialog(selections);
		});
		// 表格：全选按钮
		$btnCheckAll.on('click', function() {
			$dataTable.bootstrapTable('checkAll');
		});
		// 表格：反选按钮
		$btnInvertCheck.on('click', function() {
			var datas = $dataTable.bootstrapTable('getData');
			for (var i=0; i<datas.length; i++) {
				if (datas[i].checkStatus) {
					$dataTable.bootstrapTable('uncheck', i);
				} else {
					$dataTable.bootstrapTable('check', i);
				}
			}
		});
		// 表格：取消选择按钮
		$btnUncheckAll.on('click', function() {
			$dataTable.bootstrapTable('uncheckAll');
		});
		
		// 删除确认窗口（所选矿区下存在机架时）：确认删除按钮
		$btnDeleteConfirm.on('click', function() {
			if ($moveShelfs.prop('checked') == true) {
				var newAreaId = $chosenMoveForDelete.val();
				if (!newAreaId) {
					$moveForDeleteTip.show();
					return;
				}
				for (var i=0; i<datasTobeDeleted.length; i++) {
					datasTobeDeleted[i].shelfNewAreaIdWhenDelete = newAreaId;
				}
				doDelete(JSON.stringify(datasTobeDeleted));
			} else {
				doDelete(JSON.stringify(datasTobeDeleted));
			}
		});
		// 删除确认窗口（所选矿区下存在机架时）：重新分配机架时的目标矿区下拉列表框-值改变时隐藏提示
		$chosenMoveForDelete.on('change', function() {
			$moveForDeleteTip.hide();
		});
	}

	// 初始化页面控件
	function initWidgets() {
		$chosenMoveForDelete.chosen({allow_single_deselect: true, width:'60%'});
		$iChecks.iCheck({checkboxClass:'icheckbox_square-green',radioClass:'iradio_square-green'});
		
		$dataTable.bootstrapTable({
			height: getHeight(),
			url: 'areas',
			idField: 'id',
			//clickToSelect: true,
			search: true,
			pagination: false,
			sidePagination: 'server',
			showRefresh: true,
			showToggle: true,
			showColumns: true,
			toolbar: '#dataTableToolbar',
			iconSize: 'outline',
			icons: {
				paginationSwitchDown: 'glyphicon-collapse-down icon-chevron-down',
	            paginationSwitchUp: 'glyphicon-collapse-up icon-chevron-up',
	            refresh: 'glyphicon-repeat',
				toggle: 'glyphicon-list-alt',
				columns: 'glyphicon-list',
	            detailOpen: 'glyphicon-plus icon-plus',
	            detailClose: 'glyphicon-minus icon-minus'
			},
			editable: true,
			onEditableSave: function(field, row, oldValue, $el) {
				doPut(JSON.stringify(row));
			},
			columns: [
				{
					field: 'checkStatus',
					checkbox: true,
					align: 'center'
				},
				{
					field: 'id',
					title: 'ID',
					align: 'center',
					visible: false
				},
				{
					field: 'name',
					title: '矿区名称',
					halign: 'center',
					align: 'left',
					sortable: true,
					sortName: 'name',
					editable: {
						type: 'text',
						validate: function(value) {
							value = $.trim(value);
							if (!value || value.length < 2 || value.length > 80) {
								return '矿区名称必须为2-80个字符。';
							}
							return '';
						}
					}
				},
				{
					field: 'shelfCount',
					title: '下属机架数量',
					align: 'center'
				},
				{
					field: 'enable',
					title: '可用状态',
					align: 'center',
					formatter: function(value, row, index) {
						return value == true ? '<img src="../img/icon/icon-enabled.png" width="20" height="20" />' : '<img src="../img/icon/icon-disabled.png" width="20" height="20" />';
					}
				},
				{
					field: 'remark',
					title: '备注',
					halign: 'center',
					align: 'left',
					editable: {
						type: 'text',
						validate: function(value) {
							value = $.trim(value);
							if (!value && value.length > 300) {
								return '备注不能超过300个字符。';
							}
							return '';
						}
					}
				},
				{
					field: 'operate',
					title: '操作',
					align: 'center',
					events: window.operateEvents = {
							'click .edit': function (e, value, row, index) {
								openEditDialog(row);
					        },
					        'click .delete': function (e, value, row, index) {
					        	var rows = new Array(1);
					        	rows[0] = row;
					        	openRemoveDialog(rows);
					        }
					},
					formatter: function(value, row, index) {
						return [
								'<a class="edit" href="javascript:void(0)" title="修改">',
								'<i class="glyphicon glyphicon-edit"></i>',
								'</a>  ',
								'<a class="delete" href="javascript:void(0)" title="删除">',
								'<i class="glyphicon glyphicon-remove"></i>',
								'</a>'
						       ].join('');
					}
				}
			]
		});
	}
});








